package watcherWrap

import (
	"context"
	"fmt"
	"github.com/fsnotify/fsnotify"
	"path"
	"strings"
	"uploadmp4/db"
)

var watcher *fsnotify.Watcher

func NewWatcher() {
	var err error
	watcher, err = fsnotify.NewWatcher()
	if err != nil {
		fmt.Println(err)
	}
}

func IsDirWatching(dir string) bool {
	list := watcher.WatchList()
	for _, l := range list {
		if l == dir {
			return true
		}
	}
	return false
}

func Add(dir string) {
	// 监听的目录
	fmt.Printf("Monitoring changes in %s...\n", dir)
	dirToWatch := dir
	var err = watcher.Add(dirToWatch)
	if err != nil {
		fmt.Println("Error:", err, dir)
		return
	}
}
func Remove(dir string) {
	watcher.Remove(dir)
}

func Run(ctx context.Context) {
	// 启动一个goroutine来处理事件
	go func() {
		for {
			select {
			case event, ok := <-watcher.Events:
				if !ok {
					return
				}
				if event.Op == fsnotify.Create {
					baseName := path.Base(event.Name)
					if strings.HasPrefix(baseName, ".") {
						continue
					}
					if !strings.HasSuffix(baseName, ".mp4") {
						continue
					}
					fmt.Println("find new mp4", event.Name)
					db.SaveMp4ToDb(ctx, event.Name)
				}
			case err, ok := <-watcher.Errors:
				if !ok {
					return
				}
				fmt.Println("watcher Error:", err)
			}
		}
	}()
}
